import { image } from '@kit.ImageKit';
import { PathUtil } from '../04-PathUtil/PathUtil';
import { FileManager } from '../file_manager/FileManager';

export class ImageManager {
  static async pixelMapFromSandbox(filePath: string): Promise<image.PixelMap> {
    let arrayBuffer = FileManager.readBytesFromSandboxFileSync(filePath);
    let pixelMap = await this.arrayBufferToPixeMap(arrayBuffer);
    return pixelMap;
  }

  static async arrayBufferToPixeMap(arrayBuffer: ArrayBuffer): Promise<image.PixelMap> {
    const imageSource: image.ImageSource = image.createImageSource(arrayBuffer);
    let decodingOptions: image.DecodingOptions = {
      editable: false,
      desiredPixelFormat: 3,
    }
    // 创建pixelMap并进行简单的旋转和缩放
    let pixelMap = await imageSource.createPixelMap(decodingOptions)
      .catch((e) => {
        let err = e as Error;
        console.log(err.message)
        throw err;
      })
    return pixelMap;
  }

  /**
   * 这种压缩不是很精准.
   * @param pixelMap
   * @param filePath
   * @param quality 0-100
   */
  static async saveBitmapAsJpgToSandbox(pixelMap: image.PixelMap, filePath: string, quality: number) {
    const imagePackerApi = image.createImagePacker();
    // if(quality == undefined) {
    //    quality = 98;
    // }
    // if (maxSizeInKB) {
    //   //这个比例不是那么准确
    //   let originSize = (pixelMap.getPixelBytesNumber() * 4)
    //   quality = maxSizeInKB * 1024 / originSize * 100 * 10 * 2;
    // }
    let packOpts: image.PackingOption = { format: "image/jpeg", quality: quality };
    let arrayBuffer = await imagePackerApi.packing(pixelMap, packOpts);
    FileManager.writeToFile(arrayBuffer, filePath);
  }


  /**
   * 将图片压缩至不超过指定大小.
   * @param srcFilePath
   * @param dstFilePath
   * @param maxSizeInKB
   * @returns
   */
  static async compressImage(srcFilePath: string, dstFilePath: string | undefined, maxSizeInKB: number) {
    if (!dstFilePath) {
      let fileName = PathUtil.getName(srcFilePath);
      let fileTitle = FileManager.getFileTitleFromName(fileName);
      let dir = FileManager.getParentDir(srcFilePath);
      let newFileTitle = `${fileTitle}_compressed`
      let fileExt = FileManager.getFileExtFromName(fileName);
      dstFilePath = `${dir}/${newFileTitle}.${fileExt}`
    }
    FileManager.copyFileToUri(srcFilePath, dstFilePath);
    //对于一个宽高的图片多次使用一个quality进行压缩,图片大小不变
    //只能采用多个quality去试.
    let dstSize = FileManager.getFileInfo(dstFilePath).size;
    let maxSize = maxSizeInKB * 1024;
    let size2 = FileManager.getFileSizeString(dstFilePath);

    if (dstSize < maxSize) {
      return dstFilePath;
    }

    let quality = 100;
    let pixelMap = await this.pixelMapFromSandbox(srcFilePath);
    while (dstSize > maxSize) {
      quality /= 2;
      await this.saveBitmapAsJpgToSandbox(pixelMap, dstFilePath, quality);
      dstSize = FileManager.getFileInfo(dstFilePath).size;
      size2 = FileManager.getFileSizeString(dstFilePath);
      console.log("");
    }
    return dstFilePath;
  }
}